import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

// void main() => runApp(const DingTalkApp());
//
// class DingTalkApp extends StatelessWidget {
//   const DingTalkApp({super.key});
//
//   @override
//   Widget build(BuildContext context) {
//     return MaterialApp(
//       title: '钉钉风格示例',
//       theme: ThemeData(
//         primarySwatch: Colors.blue,
//         appBarTheme: const AppBarTheme(
//           elevation: 0,
//           backgroundColor: Colors.white,
//           foregroundColor: Colors.black,
//         ),
//       ),
//       home: const ChatDetailPage(),
//     );
//   }
// }

class ChatDetailPage extends StatefulWidget {
  const ChatDetailPage({super.key});

  @override
  State<ChatDetailPage> createState() => _ChatDetailPageState();
}

class _ChatDetailPageState extends State<ChatDetailPage> {
  int _selectedIndex = 0;

  final List<Widget> _pages = [
    const ChatScreen(),
    const NotificationScreen(),
  ];

  void _onItemTapped(int index) {
    setState(() => _selectedIndex = index);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _pages[_selectedIndex],
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _selectedIndex,
        selectedItemColor: Colors.blue,
        unselectedItemColor: Colors.grey,
        items: const [
          BottomNavigationBarItem(
            icon: Icon(Icons.chat_bubble_outline),
            label: '消息',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.notifications_none),
            label: '通知',
          ),
        ],
        onTap: _onItemTapped,
      ),
    );
  }
}

// 聊天页面实现
class ChatScreen extends StatefulWidget {
  const ChatScreen({super.key});

  @override
  State<ChatScreen> createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> {
  final TextEditingController _controller = TextEditingController();
  final List<Message> _messages = [
    Message(
      content: '你好！项目文档准备好了吗？',
      isMe: false,
      time: DateTime.now().subtract(const Duration(minutes: 5)),
    ),
    Message(
      content: '已经准备好了，马上发到群里',
      isMe: true,
      time: DateTime.now().subtract(const Duration(minutes: 3)),
    ),
  ];

  void _sendMessage() {
    if (_controller.text.trim().isEmpty) return;

    setState(() {
      _messages.add(Message(
        content: _controller.text,
        isMe: true,
        time: DateTime.now(),
      ));
      _controller.clear();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('项目沟通群'),
        actions: [
          IconButton(icon: const Icon(Icons.more_horiz), onPressed: () {}),
        ],
      ),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              reverse: true,
              padding: const EdgeInsets.all(8),
              itemCount: _messages.length,
              itemBuilder: (context, index) {
                final message = _messages.reversed.toList()[index];
                return _ChatBubble(message: message);
              },
            ),
          ),
          _ChatInput(
            controller: _controller,
            onSend: _sendMessage,
          ),
        ],
      ),
    );
  }
}

class _ChatBubble extends StatelessWidget {
  final Message message;

  const _ChatBubble({required this.message});

  @override
  Widget build(BuildContext context) {
    return Align(
      alignment: message.isMe ? Alignment.centerRight : Alignment.centerLeft,
      child: Container(
        margin: const EdgeInsets.symmetric(vertical: 4),
        constraints: const BoxConstraints(maxWidth: 280),
        child: Column(
          crossAxisAlignment: message.isMe
              ? CrossAxisAlignment.end
              : CrossAxisAlignment.start,
          children: [
            Container(
              padding: const EdgeInsets.symmetric(
                horizontal: 14,
                vertical: 10,
              ),
              decoration: BoxDecoration(
                color: message.isMe
                    ? Colors.blue[100]
                    : Colors.grey[200],
                borderRadius: BorderRadius.circular(12),
              ),
              child: Text(message.content),
            ),
            Padding(
              padding: const EdgeInsets.only(top: 4),
              child: Text(
                DateFormat('HH:mm').format(message.time),
                style: TextStyle(
                  fontSize: 12,
                  color: Colors.grey[600],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _ChatInput extends StatelessWidget {
  final TextEditingController controller;
  final VoidCallback onSend;

  const _ChatInput({
    required this.controller,
    required this.onSend,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(8),
      color: Colors.grey[100],
      child: Row(
        children: [
          Expanded(
            child: TextField(
              controller: controller,
              decoration: InputDecoration(
                hintText: '输入消息...',
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(20),
                  borderSide: BorderSide.none,
                ),
                filled: true,
                contentPadding: const EdgeInsets.symmetric(horizontal: 16),
              ),
              onSubmitted: (_) => onSend(),
            ),
          ),
          IconButton(
            icon: const Icon(Icons.send, color: Colors.blue),
            onPressed: onSend,
          ),
        ],
      ),
    );
  }
}

// 通知页面实现
class NotificationScreen extends StatelessWidget {
  const NotificationScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('通知'),
        actions: [
          IconButton(
            icon: const Icon(Icons.checklist),
            onPressed: () {},
          ),
        ],
      ),
      body: ListView(
        children: const [
          _NotificationItem(
            type: NotificationType.system,
            title: '系统升级通知',
            time: '09:30',
          ),
          _NotificationItem(
            type: NotificationType.friendRequest,
            title: '新的好友请求 - 张伟',
            time: '昨天',
            status: '待处理',
          ),
          _NotificationItem(
            type: NotificationType.groupInvite,
            title: '邀请加入「项目讨论组」',
            time: '2023-08-01',
            status: '已同意',
          ),
        ],
      ),
    );
  }
}

class _NotificationItem extends StatelessWidget {
  final NotificationType type;
  final String title;
  final String time;
  final String? status;

  const _NotificationItem({
    required this.type,
    required this.title,
    required this.time,
    this.status,
  });

  IconData _getIcon() {
    switch (type) {
      case NotificationType.system:
        return Icons.info_outline;
      case NotificationType.friendRequest:
        return Icons.person_add_alt_1;
      case NotificationType.groupInvite:
        return Icons.group_add;
    }
  }

  Color _getColor() {
    switch (status) {
      case '待处理':
        return Colors.orange;
      case '已同意':
        return Colors.green;
      case '已拒绝':
        return Colors.red;
      default:
        return Colors.grey;
    }
  }

  @override
  Widget build(BuildContext context) {
    return ListTile(
      leading: Container(
        width: 40,
        height: 40,
        decoration: BoxDecoration(
          color: Colors.blue,
          shape: BoxShape.circle,
        ),
        child: Icon(_getIcon(), color: Colors.blue),
      ),
      title: Text(title),
      subtitle: Text(time),
      trailing: status != null
          ? Chip(
        label: Text(status!),
        backgroundColor: _getColor().withOpacity(0.1),
        labelStyle: TextStyle(color: _getColor()),
      )
          : null,
      onTap: () {},
    );
  }
}

// 数据模型
class Message {
  final String content;
  final bool isMe;
  final DateTime time;

  Message({
    required this.content,
    required this.isMe,
    required this.time,
  });
}

enum NotificationType { system, friendRequest, groupInvite }
